package br.com.hstar.server.formapgto;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import br.com.hstar.client.formapgto.FormaPgtoService;
import br.com.hstar.client.formapgto.FormaPgtoUI;
import br.com.hstar.client.util.HstarUserException;
import br.com.hstar.model.formapgto.FormaPgtoDO;
import br.com.hstar.server.DozerHelper;
import br.com.hstar.server.DozerUtility;
import br.com.hstar.server.HibernateUtility;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class FormaPgtoServiceImpl extends RemoteServiceServlet implements FormaPgtoService {

	private static final long serialVersionUID = 5032440489417959893L;

	public void saveOrUpdate(FormaPgtoUI objUI) throws HstarUserException  {
		
		FormaPgtoDO objDO = (FormaPgtoDO) DozerUtility.getMapper().map(objUI, FormaPgtoDO.class);
				
		Session sessao = HibernateUtility.getSession();
		Transaction transaction = sessao.beginTransaction();
		
		if(objUI.getId() != null) {
			sessao.update(objDO);
		} else {
			sessao.save(objDO);
		}

		transaction.commit();
		sessao.close();
	}
	
	public List listAll() {
		Session sessao = HibernateUtility.getSession();
		Criteria select = sessao.createCriteria(FormaPgtoDO.class);
		ArrayList objetos = (ArrayList)select.list();
		sessao.close();
		
		return DozerHelper.mapList(
				DozerUtility.getMapper(), 
				objetos, 
				FormaPgtoUI.class);
	}
	
	public FormaPgtoUI retrieveById(Long id) {
		Session sessao = HibernateUtility.getSession();
		Criteria cri = sessao.createCriteria(FormaPgtoDO.class);
		cri.add(Restrictions.eq("id", id));
		FormaPgtoDO objDO = (FormaPgtoDO) cri.uniqueResult();
		sessao.close();
				
		FormaPgtoUI objUI = (FormaPgtoUI) DozerUtility.getMapper().map(objDO, FormaPgtoUI.class);
		
	  	return objUI;
	}
	
	public void delete(Long id) {
		Session sessao = HibernateUtility.getSession();
		Transaction transaction = sessao.beginTransaction();

			Criteria cri = sessao.createCriteria(FormaPgtoDO.class);
			cri.add(Restrictions.eq("id", id));
			FormaPgtoDO objDO = (FormaPgtoDO) cri.uniqueResult();
			sessao.delete(objDO);

		transaction.commit();
		sessao.close();
	}
}
